<template>
  <div class="modbus-model-management">
    <div class="table-operations">
      <a-button type="primary" @click="handleAdd">新建</a-button>
      <a-button @click="handleRefresh">刷新</a-button>
    </div>

    <a-table :columns="columns" :dataSource="dataSource" :pagination="pagination" :loading="loading" rowKey="uuid">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <a-space>
            <a @click="handleEdit(record)">编辑</a>
            <a-popconfirm title="你确定要删除吗？" @confirm="handleDelete(record)">
              <a style="color: #ff4d4f">删除</a>
            </a-popconfirm>
          </a-space>

        </template>
        <template v-else-if="column.key === 'version'">
          {{ getVersionText(record.version) }}
        </template>
        <template v-else-if="column.key === 'securityLevel'">
          {{ getSecurityLevelText(record.snmpSecurityLevel) }}
        </template>
      </template>
    </a-table>

    <a-modal v-model:open="modalVisible" :title="modalTitle" width="800px" @ok="handleSubmit" @cancel="handleCancel">
      <a-form ref="formRef" :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="模型名称" name="name" :rules="[{ required: true, message: '请输入模型名称' }]">
          <a-input v-model:value="formState.name" />
        </a-form-item>
        <a-form-item label="模型描述" name="dec">
          <a-input v-model:value="formState.dec" />
        </a-form-item>
        <a-form-item label="组态模型" name="configUid" :rules="[{ required: true, message: '请选择组态模型' }]">
          <a-select v-model:value="formState.configUid" @change="changeConfigUid">
            <a-select-option v-for="option in modelOptions" :key="option.ID" :value="option.displayUid">
              {{ option.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="组态展示页面" name="PageUUID" :rules="[{ required: true, message: '请选择展示页面' }]">
          <a-select v-model:value="formState.PageUUID">
            <a-select-option v-for="option in pageOptions" :key="option.PageId" :value="option.PageId">
              {{ option.PageName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="端口" name="port" :rules="[{ required: true, message: '请输入端口号' }]">
          <a-input v-model:value="formState.port" />
        </a-form-item>
        <a-form-item label="采集数量" name="gatherNumber" :rules="[{ required: true, message: '请输入采集数量' }]">
          <a-input v-model:value="formState.gatherNumber" />
        </a-form-item>
        <a-form-item label="协议版本" name="version" :rules="[{ required: true, message: '请选择协议版本' }]">
          <a-select v-model:value="formState.version" @change="handleVersionChange">
            <a-select-option :value="1">V1</a-select-option>
            <a-select-option :value="2">V2</a-select-option>
            <a-select-option :value="3">V3</a-select-option>
          </a-select>
        </a-form-item>

        <!-- V1/V2 版本字段 -->
        <template v-if="formState.version === 1 || formState.version === 2">
          <a-form-item label="写公共体" name="writeCommunity" :rules="[{ required: true, message: '请输入写公共体' }]">
            <a-input v-model:value="formState.writeCommunity" />
          </a-form-item>
          <a-form-item label="读公共体" name="readCommunity" :rules="[{ required: true, message: '请输入读公共体' }]">
            <a-input v-model:value="formState.readCommunity" />
          </a-form-item>
        </template>

        <!-- V3 版本字段 -->
        <template v-if="formState.version === 3">
          <a-form-item label="加密等级" name="snmpSecurityLevel" :rules="[{ required: true, message: '请选择加密等级' }]">
            <a-select v-model:value="formState.snmpSecurityLevel" @change="handleSecurityLevelChange">
              <a-select-option :value="1">不授权不加密</a-select-option>
              <a-select-option :value="2">授权不加密</a-select-option>
              <a-select-option :value="3">授权加密</a-select-option>
            </a-select>
          </a-form-item>

          <template v-if="formState.snmpSecurityLevel > 1">
            <a-form-item label="用户名" name="snmpUserName" :rules="[{ required: true, message: '请输入用户名' }]">
              <a-input v-model:value="formState.snmpUserName" />
            </a-form-item>
            <a-form-item label="身份验证算法" name="snmpAuthAlgorithm" :rules="[{ required: true, message: '请选择身份验证算法' }]">
              <a-select v-model:value="formState.snmpAuthAlgorithm">
                <a-select-option :value="1">MD5</a-select-option>
                <a-select-option :value="2">SHA</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="密码" name="snmpUserPassword" :rules="[{ required: true, message: '请输入密码' }]">
              <a-input-password v-model:value="formState.snmpUserPassword" />
            </a-form-item>
          </template>

          <template v-if="formState.snmpSecurityLevel > 2">
            <a-form-item label="隐私加密算法" name="snmpPrivacyAlgorithm" :rules="[{ required: true, message: '请选择隐私加密算法' }]">
              <a-select v-model:value="formState.snmpPrivacyAlgorithm">
                <a-select-option :value="1">DES</a-select-option>
                <a-select-option :value="2">AES</a-select-option>
                <a-select-option :value="3">AES192</a-select-option>
                <a-select-option :value="4">AES256</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="隐私密码" name="snmpPrivacyPassword" :rules="[{ required: true, message: '请输入隐私密码' }]">
              <a-input-password v-model:value="formState.snmpPrivacyPassword" />
            </a-form-item>
          </template>
        </template>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { message, Modal } from 'ant-design-vue';
import { cvaiApi } from '/@/api/system/cvai-api';


const columns = [
  {
    title: '序号',
    dataIndex: 'ID',
    key: 'ID',
    width: 80,
  },
  {
    title: '模型名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '模型描述',
    dataIndex: 'dec',
    key: 'dec',
  },
  {
    title: '协议版本',
    key: 'version',
  },
  {
    title: '加密等级',
    key: 'securityLevel',
  },
  {
    title: '操作',
    key: 'action',
    width: '200px',
  },
];

const dataSource = ref([]);
const loading = ref(false);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
});

const currentModelId = ref(null);
const modalVisible = ref(false);
const modalTitle = ref('新增SNMP数据模型');
const formRef = ref();
const formState = reactive({
  uuid: '',
  name: '',
  dec: '',
  configUid: '',
  PageUUID: '',
  port: '',
  version: '',
  gatherNumber: '',
  writeCommunity: '',
  readCommunity: '',
  snmpSecurityLevel: '',
  snmpUserName: '',
  snmpAuthAlgorithm: '',
  snmpUserPassword: '',
  snmpPrivacyAlgorithm: '',
  snmpPrivacyPassword: '',
});

// 获取版本文本
const getVersionText = (version) => {
  switch (version) {
    case 1: return 'V1';
    case 2: return 'V2';
    case 3: return 'V3';
    default: return '未知';
  }
};

// 获取安全等级文本
const getSecurityLevelText = (level) => {
  switch (level) {
    case 1: return '不授权不加密';
    case 2: return '授权不加密';
    case 3: return '授权加密';
    default: return '未知';
  }
};

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true;

    cvaiApi.getSnmpmodellist({ type: 1 }).then((res) => {
      dataSource.value = res.list; // 将数据模型选项存储到 modelOptions 中
    });

    pagination.total = dataSource.value.length;
  } catch (error) {
    message.error('加载数据失败');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 版本变更处理
const handleVersionChange = (version) => {
  // 重置相关字段
  if (version !== 3) {
    formState.snmpSecurityLevel = '';
    formState.snmpUserName = '';
    formState.snmpAuthAlgorithm = '';
    formState.snmpUserPassword = '';
    formState.snmpPrivacyAlgorithm = '';
    formState.snmpPrivacyPassword = '';
  } else {
    formState.writeCommunity = '';
    formState.readCommunity = '';
  }
};

// 安全等级变更处理
const handleSecurityLevelChange = (level) => {
  if (level < 3) {
    formState.snmpPrivacyAlgorithm = '';
    formState.snmpPrivacyPassword = '';
  }
  if (level < 2) {
    formState.snmpUserName = '';
    formState.snmpAuthAlgorithm = '';
    formState.snmpUserPassword = '';
  }
};

// 新增
const handleAdd = () => {
  modalTitle.value = '新增SNMP数据模型';
  resetForm();
  modalVisible.value = true;
};

// 编辑
const handleEdit = async (record) => {
  modalTitle.value = '编辑SNMP数据模型';
  currentModelId.value = record.uuid;
  resetForm();
  try {
    cvaiApi.snmpmodelget({ uuid: record.uuid }).then((response) => {
      if (response.code == 200) {
        Object.assign(formState, response.data);
      } else {
        Object.assign(formState, record);
      }
    });
    modalVisible.value = true;
  } catch (error) {
    message.error('获取详情失败');
    console.error(error);
  }
};

// 删除
const handleDelete = (record) => {
  try {
    loading.value = true;
    cvaiApi.snmpmodeldel({ uuid: record.uuid }).then((res) => {
      if (res.code == 200) {
        message.success('删除成功');
        fetchData();
      } else {
        message.error('删除失败');
      }
    });
  } catch (error) {
    console.error('删除失败:', error);
    message.error('删除失败');
  } finally {
    loading.value = false;
  }
};

// 刷新
const handleRefresh = () => {
  fetchData();
};

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate();

    // 根据是新增还是编辑调用不同的API
    if (formState.uuid) {
      // 编辑
      const obj = {
        uuid: currentModelId.value,
        data: { ...formState },
      };
      cvaiApi.snmpmodelEdit(obj).then((res) => {
        if (res.code == 200) {
          message.success('编辑成功');
          fetchData();
          modalVisible.value = false;
        } else {
          message.error('编辑失败');
        }
      });
    } else {
      // 新增
      cvaiApi.snmpmodeladd(formState).then((res) => {
        if (res.code == 2002) {
          message.success('新建成功');
          fetchData();
          modalVisible.value = false;
        } else {
          message.error('新建失败');
        }
      });
    }
    modalVisible.value = false;
    fetchData();
  } catch (error) {
    console.error(error);
    if (error.errorFields) {
      message.error('请填写完整表单');
    } else {
      message.error('操作失败');
    }
  }
};

// 取消
const handleCancel = () => {
  modalVisible.value = false;
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
  formState.uuid = '';
  formState.name = '';
  formState.dec = '';
  formState.configUid = '';
  formState.PageUUID = '';
  formState.port = '';
  formState.version = '';
  formState.gatherNumber = '';
  formState.writeCommunity = '';
  formState.readCommunity = '';
  formState.snmpSecurityLevel = '';
  formState.snmpUserName = '';
  formState.snmpAuthAlgorithm = '';
  formState.snmpUserPassword = '';
  formState.snmpPrivacyAlgorithm = '';
  formState.snmpPrivacyPassword = '';
};
//组态模型options
const modelOptions = ref([]);
const pageOptions = ref([]);
function getDisplayModelListOptions() {
  cvaiApi.getDisplayModelList().then((res) => {
    modelOptions.value = res.list;
  });
}
//联动调用接口获取List
const changeConfigUid = (value) => {
  cvaiApi.getMonitorDetail({ muid: value }).then((res) => {
    if (res.code == 0) {
      pageOptions.value = res.layer;
    }
  });
};

onMounted(() => {
  fetchData();
  getDisplayModelListOptions(); // 获取组态模型列表
});
</script>

<style scoped>
.modbus-model-management {
  padding: 20px;
  background: #fff;
}

.table-operations {
  margin-bottom: 16px;
}

.table-operations>button {
  margin-right: 8px;
}
</style>